package leetcode.mthread.交替打印FooBar;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 同步原语实现
 *
 * @author scylla
 * @version V1.0
 * @project echo-java-base
 * @title
 * @package leetcode.mthread.交替打印FooBar
 * @since 2021/12/7 1:34 下午
 */
public class FooBarSynchronized {


    private int n;

    private final AtomicBoolean fooPrinted = new AtomicBoolean(false);

    public FooBarSynchronized(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (this) {

                while (fooPrinted.get()) {
                    this.wait();
                }
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();

                fooPrinted.set(true);

                this.notifyAll();
            }


        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (this) {
                while (!fooPrinted.get()) {
                    this.wait();
                }

                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();

                fooPrinted.set(false);

                this.notifyAll();
            }


        }
    }
}
